#include <list>
#include <iostream> 
#include <sstream> 
#include <fstream>

#include "polimr.h"

class WordCounter : Mapper
{
public:
  virtual void map(string input)
  {
    stringstream stream(input);
    string word;
    while (stream)
      {
	stream >> word;
	if (word.size() > 0)
	  this->emit(word, "1");
	word.clear(); 
      }
  } 
}; 

REGISTER_MAPPER(WordCounter)

class Adder : Reducer
{
public:
  virtual void reduce(const list<string>& values)
  {
    int sum = 0; 
    int value; 
    for (list<string>::const_iterator valit = values.begin();
	 valit != values.end(); valit++)
      {
	value = atoi((*valit).c_str()); 
	sum += value; 
      }
    char finval[255]; 
    sprintf(finval, "%d", sum); 
    this->emit(string(finval)); 
  }
}; 

REGISTER_REDUCER(Adder)


int main(void)
{
  MapReduce::mrconfig params; 
  int argc = 6; 
  const char *argv[5] = {"mrinput.txt", 
			 "mrinput2.txt", 
			 "mrinput3.txt", 
			 "mrinput4.txt", 
			 "mrinput5.txt"}; 
  
  string file; 
  for (int i = 0; i < argc - 1; i++)
    {
      file = argv[i];
      params.input.push_back(file); 
    }
  
  params.M = 3; 
  params.R = 2;
  params.outname = "wc-res"; 
  
  MapReduce::mapreduce(params);
  return 0; 
}

